//
//  AppDelegate.m
//  LINNER
//
//  Created by wei wang on 2017/3/30.
//  Copyright © 2017年 weiwang. All rights reserved.
//

#import "AppDelegate.h"
#import <ExternalAccessory/ExternalAccessory.h>
#import "NSString+Helper.h"
#import "LightningUpdateViewController.h"
#import "LINNERBurnTime.h"
#import "SWRevealViewController.h"
#import "PersonMenuController.h"
#import "ViewController.h"
#import "MainSlideViewController.h"
#import "WelcomeViewController.h"
#import "LightningModel.h"

@interface AppDelegate ()<DeviceToConnectDelegate,AVAudioPlayerDelegate>{
    
    dispatch_source_t timer;
    //每次进入app时先判断 在那个时间段
    NSString *everyTime;
    NSInteger tagIndex; //0 1 2 3 0:12小时以下  1:24小时一下 2:36小时以下 3:超出
    
}

// 开机动画
@property (strong, nonatomic) UIView *splashView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 启动图显示时间
//    sleep(2);
    
    self.GetheadsetEQ = -1;
    self.GetheadsetBattery = -1;
    self.GetheadsetVoice = -1;
    self.GetheadsetLight = -1;
    self.GetheadsetLaugage = -1;
    self.burnMode = -1;
    
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    self.deviceToConnect = [DeviceToConnect sharedController];
    self.deviceToConnect.delegate = self;
    [self.deviceToConnect addNotice];
    [self.deviceToConnect findEQlocation];
    
    
    self.lightingConnet = NO;
    self.linnerConnet = NO;
    
    NSArray *lightArray = [LightningModel selectAllObject];
    if (lightArray.count == 0)
    {
        LightningModel *lightningModel = [[LightningModel alloc] init];
        lightningModel.eqstate = [NSString stringWithFormat:@"%li",(long)self.deviceToConnect.eqstate];
        [lightningModel insertObject];
    }
    else
    {
        NSArray *array = [LightningModel selectAllObject];
        LightningModel *model = array.lastObject;
        model.eqstate = [NSString stringWithFormat:@"%li",(long)self.deviceToConnect.eqstate];
        [model insertObject];
    }
    
    [self EAS];
    
//    UINavigationController *loginVC =(UINavigationController *)[main instantiateViewControllerWithIdentifier:@"ViewController"];
    
//    SWRevealViewController *menu = [[SWRevealViewController alloc] initWithRearViewController:[PersonMenuController new] frontViewController:loginVC];
//    self.window.rootViewController = menu;
    
//    UIStoryboard *main=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    

//    self.window.rootViewController = nav;

    WelcomeViewController *vc = [[WelcomeViewController alloc] init];
    self.window.rootViewController = vc;


    return YES;
}

- (void)startLaunchingAnimation
{
    [self.window makeKeyAndVisible];
//    UIStoryboard *lauch = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
//    ViewController *lauchVC = [lauch instantiateViewControllerWithIdentifier:@"LauchScreen"];
//    lauchVC.view.backgroundColor = [UIColor blueColor];
    self.splashView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
    self.splashView.backgroundColor = [UIColor blueColor];
    [self.window addSubview:self.splashView];
    [self.window bringSubviewToFront:self.splashView];
    
    
    [NSThread sleepForTimeInterval:3.0f];
    [self.splashView removeFromSuperview];
}

#pragma mark -- 监听系统音乐，当播放系统音乐时自动关闭煲机模式
// 接收通知方法
- (void)AVAudioSessionInterruptionNotification: (NSNotification *)notificaiton {
    NSLog(@"%@", notificaiton.userInfo);
    
    AVAudioSessionInterruptionType type = [notificaiton.userInfo[AVAudioSessionInterruptionTypeKey] intValue];
    if (type == AVAudioSessionInterruptionTypeBegan)
    {
//        if (self.avAudioPlayer.isPlaying == YES)
//        {
            self.isBurn = NO;
            [self stop];
//        }
        
    }
}

- (void)EAS{
    
    
    // load the UISupportedExternalAccessory property to know which protocolStrings are registered in the app
    NSBundle *mainBundle = [NSBundle mainBundle];
    self.supportedProtocolsStrings = [mainBundle objectForInfoDictionaryKey:@"UISupportedExternalAccessoryProtocols"];
#pragma mark - --------------------------linner--------------------------
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_sessionDataReceived:) name:EADSessionDataReceivedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disconnectDevice) name:BREAK object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AVAudioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
    
    [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
    
    _eaSessionController = [EADSessionController sharedController];
    _accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
    //第一次进入如果有就直接连接
    if ([_accessoryList count] == 0) {
        
        NSLog(@"没有设备");
        
    } else {
        
        NSLog(@"有设备");
        _selectedAccessory = [_accessoryList firstObject];
        NSArray *protocolStrings = [_selectedAccessory protocolStrings];
        for(NSString *protocolString in protocolStrings){
            
            if (_selectedAccessory)
            {
                BOOL  matchFound = FALSE;
                for ( NSString *item in self.supportedProtocolsStrings)
                {
                    if ([item compare: protocolString] == NSOrderedSame)
                    {
                        matchFound = TRUE;
                        NSLog(@"match found - protocolString %@", protocolString);
                    }
                }
                
                
                if (matchFound == FALSE)
                {
                    
                    
                    
                    NSLog(@"此设备协议不支持");
                    _selectedAccessory = nil;
                    
                    
                }
                else
                {//
                    
                    
                    
                    [self.eaSessionController setupControllerForAccessory:_selectedAccessory
                                                       withProtocolString:protocolString];
                    
                    self.accessory = [self.eaSessionController accessory];
                    
                    
                    
                    [self.eaSessionController openSession];
                    
                    if ([self.accessory.serialNumber length] == 12) {
                        
                        
                        self.linnerConnet = YES;
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"linnerConnect" object:nil];
                        
                        [self registerLinner];
                        
                    }
                    
                    
                }
            }
            
            _selectedAccessory = nil;
            
            
            
        }
        
        
    }
    

    
}




#pragma mark - --------------------------注册耳机通知 并保存这个蓝牙设备地址--------------------------
- (void)registerLinner{
    
      //1.首先判断通知有没有被注册
    
    [self checkRegister];
    
    
}

- (void)checkRegister{
    NSString *sendata = @"aa0140810b";
    const char *buf = [sendata UTF8String];
    NSMutableData *data = [NSMutableData data];
    if (buf)
    {
        uint32_t len = (uint32_t)strlen(buf);
        
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [data appendBytes:(void *)(&tmp) length:1];
            }
            else
            {
                break;
            }
        }
        
        NSLog(@"发送%@",data);
        [[EADSessionController sharedController] writeData:data];
    }
    

}

#pragma mark - --------------------------注册只注册一次以免死循环--------------------------
- (void)wwcheck{
    
    NSString *sendata = @"aa0140010b";
    const char *buf = [sendata UTF8String];
    NSMutableData *data = [NSMutableData data];
    if (buf)
    {
        uint32_t len = (uint32_t)strlen(buf);
        
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [data appendBytes:(void *)(&tmp) length:1];
            }
            else
            {
                break;
            }
        }
        
        NSLog(@"发送%@",data);
        [[EADSessionController sharedController] writeData:data];
    }
    

    
    
    
}

#pragma mark - --------------------------linner--------------------------
#pragma mark Internal
//系统连接设备后，找到的
- (void)_accessoryDidConnect:(NSNotification *)notification {
    EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    _accessoryList = [NSMutableArray array];

   // [SVProgressHUD showInfoWithStatus:@"测试"];
    
    if ([connectedAccessory.modelNumber isEqualToString:@"Rihanna"]) {
        [_accessoryList addObject:connectedAccessory];

    }
    
    if ([_accessoryList count] == 0) {
        
        
    } else {
        
        _selectedAccessory = [_accessoryList firstObject];
        for (EAAccessory *OBC in _accessoryList) {
            if (OBC.isConnected == YES) {
                  _selectedAccessory = OBC;
                break;
            }
        }
        
        if (_selectedAccessory.isConnected == NO) {
            return;
        }
        NSArray *protocolStrings = [_selectedAccessory protocolStrings];
        for(NSString *protocolString in protocolStrings){
            
            if (_selectedAccessory)
            {
                BOOL  matchFound = FALSE;
                for ( NSString *item in self.supportedProtocolsStrings)
                {
                    if ([item compare: protocolString] == NSOrderedSame)
                    {
                        matchFound = TRUE;
                        NSLog(@"match found - protocolString %@", protocolString);
                    }
                }
                
                
                if (matchFound == FALSE)
                {
                    
                    
                  //  [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"此设备协议不支持")];
                  
                    _selectedAccessory = nil;
                    
                    
                }
                else
                {//这个属于连接成功跳转
                    
                    [self.eaSessionController setupControllerForAccessory:_selectedAccessory
                                                       withProtocolString:protocolString];
                    self.accessory = [self.eaSessionController accessory];
                    
                    [self.eaSessionController openSession];
                    
                    if ([self.accessory.serialNumber length] == 12)
                    {
                        self.linnerConnet = YES;
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"linnerConnect" object:nil];
                        
                        [self registerLinner];
                    }
                }
            }
            _selectedAccessory = nil;
        }
    }
    
    NSLog(@"Linner耳机已经连接");

  /*  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([_accessoryList count] - 1) inSection:0];
    [[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
   */
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification {
    EAAccessory *disconnectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    
    if ([disconnectedAccessory.modelNumber isEqualToString:@"Rihanna"]) {
        if (disconnectedAccessory.connected == YES) {
            
        }else{
            
            [_accessoryList removeAllObjects];
            self.linnerConnet = NO;
            if (self.avAudioPlayer.isPlaying == YES)
            {
                self.isBurn = NO;
                [self stop];
            }

            [[NSNotificationCenter defaultCenter] postNotificationName:@"DislinnerConnect" object:nil];
            [self.eaSessionController closeSession];
        }

    }

    
    NSLog(@"Linner耳机已经断开连接");


    /*
    for(EAAccessory *accessory in _accessoryList) {
        if ([accessory.modelNumber isEqualToString:disconnectedAccessory.modelNumber]) {
            
            



        }
     
            //取消通知
            NSString *sendata = @"aa0140020b";
            const char *buf = [sendata UTF8String];
            NSMutableData *data = [NSMutableData data];
            if (buf)
            {
                uint32_t len = (uint32_t)strlen(buf);
                
                char singleNumberString[3] = {'\0', '\0', '\0'};
                uint32_t singleNumber = 0;
                for(uint32_t i = 0 ; i < len; i+=2)
                {
                    if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
                    {
                        singleNumberString[0] = buf[i];
                        singleNumberString[1] = buf[i + 1];
                        sscanf(singleNumberString, "%x", &singleNumber);
                        uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                        [data appendBytes:(void *)(&tmp) length:1];
                    }
                    else
                    {
                        break;
                    }
                }
                
                NSLog(@"发送%@",data);
                [[EADSessionController sharedController] writeData:data];
            }

            
     
            break;
     
        }
       */
  



}

- (void)_sessionDataReceived:(NSNotification *)notification
{
    EADSessionController *sessionController = (EADSessionController *)[notification object];
    uint32_t bytesAvailable = 0;
    while ((bytesAvailable = (uint32_t)[sessionController readBytesAvailable]) > 0) {
        NSData *data = [sessionController readData:bytesAvailable];
        if (data) {
            
            NSLog(@"返回的date:%@",data);
            NSString *dataresult = [NSString convertDataToHexStr:data];
            
            NSString *resulthead = [dataresult substringWithRange:NSMakeRange(4, 4)];
            NSString *resultend  = [dataresult substringWithRange:NSMakeRange([dataresult length]-2, 2)];
            NSString *resultsecond = [dataresult substringWithRange:NSMakeRange([dataresult length]-4, 4)];
            
            NSLog(@"%@,%@",resulthead,resultend);
            
            [self linnerStatus:resulthead and:resultend DataResult:resultsecond];
            
        }
    }
    
    
}

- (void)linnerStatus:(NSString *)headData and:(NSString *)endData DataResult:(NSString *)DataResult{
    /* 00成功  05失败 03失败
    设置耳机eq aa01 8214
    获得耳机eq aa01 8294
    设置耳机语音提示 aa01 8212
    获得耳机语音提示状态 aa01 8292
    设置耳机降噪/监听 aa01 822c
    获得耳机降噪/监听状态 aa02 82ac
    设置耳机效果灯 aa01 822e
    获得耳机效果灯状态 aa02 82ae
    注册通知 aa01 c001
    获得通知状态 aa01 c081
    取消通知 aa01 c002
    事件通知 aa02 c003
    进入OTA升级模式请求 cc01 8260
    OTA 下载数据 cc02 8261
     */
    
    if ([headData isEqualToString:@"8214"]) {//设置耳机
        
        if ([endData isEqualToString:@"00"]) {
            
            NSLog(@"设置耳机eq成功");
            
        }else if ([endData isEqualToString:@"05"]){
            
            NSLog(@"设置耳机eq失败");
            /*获取耳机eq状态*/
            NSString *sendata = @"aa000294";
            const char *buf = [sendata UTF8String];
            NSMutableData *data = [NSMutableData data];
            if (buf)
            {
                uint32_t len = (uint32_t)strlen(buf);
                
                char singleNumberString[3] = {'\0', '\0', '\0'};
                uint32_t singleNumber = 0;
                for(uint32_t i = 0 ; i < len; i+=2)
                {
                    if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
                    {
                        singleNumberString[0] = buf[i];
                        singleNumberString[1] = buf[i + 1];
                        sscanf(singleNumberString, "%x", &singleNumber);
                        uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                        [data appendBytes:(void *)(&tmp) length:1];
                    }
                    else
                    {
                        break;
                    }
                }
                
                [[EADSessionController sharedController] writeData:data];
            }

        }
        
    }else if ([headData isEqualToString:@"8294"]){//获取耳机
        
        if ([endData isEqualToString:@"00"]) {
            
            NSLog(@"均衡模式");
            self.GetheadsetEQ = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETEQ object:nil];

        }else if ([endData isEqualToString:@"01"]){
            
            NSLog(@"低音");
            self.GetheadsetEQ = 1;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETEQ object:nil];

        }else if ([endData isEqualToString:@"02"]){
            
            NSLog(@"人声");
            self.GetheadsetEQ = 2;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETEQ object:nil];

        }else if ([endData isEqualToString:@"03"]){
            
            if ([DataResult isEqualToString:@"0003"]) {
                
                NSLog(@"高音");
                self.GetheadsetEQ = 3;
                [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETEQ object:nil];

            }else{
                
                NSLog(@"失败：获取资源异常");
                self.GetheadsetEQ = -1;

            }
            
        }

        
    }else if ([headData isEqualToString:@"8302"]){//获取电量
        
        if ([DataResult isEqualToString:@"0203"]) {
            
            NSLog(@"失败：获取资源异常");
            
        }else{

            self.GetheadsetBattery = [endData intFromHexString];
            
            NSLog(@"%ld",(long)self.GetheadsetBattery);
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETBATTERY object:nil];
        
        }
    }else if ([headData isEqualToString:@"82ac"]||[headData isEqualToString:@"822c"]){//获取耳机降噪／监听状态 为了对应做了一下判断
        
        if ([endData isEqualToString:@"00"])
        {
            
            NSLog(@"耳机当前模式为正常模式");
            self.GetheadsetVoice = 0;
            
        }
        else if ([endData isEqualToString:@"01"])
        {
            
            NSLog(@"耳机当前模式为出行模式");
            self.GetheadsetVoice = 3;
            
        }
        else if ([endData isEqualToString:@"02"])
        {
            
            NSLog(@"耳机当前模式为监听模式");
            self.GetheadsetVoice = 4;
            
        }
        else if ([endData isEqualToString:@"03"])
        {
            
            NSLog(@"耳机当前模式为风中模式");
            self.GetheadsetVoice = 1;
            
        }
        else if ([endData isEqualToString:@"04"])
        {
            
            NSLog(@"耳机当前模式为室内模式");
            self.GetheadsetVoice = 2;
            
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];

    
    }else if ([headData isEqualToString:@"82ae"]){//获取耳机效果灯
        
        if ([endData isEqualToString:@"00"]) {
            
            NSLog(@"效果灯常关模式");
            self.GetheadsetLight = 3;
            
        }else if ([endData isEqualToString:@"01"]){
            
            NSLog(@"效果灯常亮模式");
            self.GetheadsetLight = 1;
            
        }else if ([endData isEqualToString:@"02"]){
            
            NSLog(@"效果灯默认模式");
            self.GetheadsetLight = 0;
            
        }else if ([endData isEqualToString:@"03"]){
            
            NSLog(@"效果灯呼吸灯模式");
            self.GetheadsetLight = 2;
            
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETLIGHT object:nil];
        
        
    }else if ([headData isEqualToString:@"8292"]){//获取耳机语言
        
        if ([endData isEqualToString:@"00"]) {
            
            NSLog(@"当前语音提示是英文");
            self.GetheadsetLaugage = 1;
            
        }else if ([endData isEqualToString:@"01"]){
            
            NSLog(@"当前语音提示是中文");
            self.GetheadsetLaugage = 0;
            
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETLAGUAGE object:nil];
        
        
    }else if ([headData isEqualToString:@"c002"]){//取消通知
        
        if ([endData isEqualToString:@"0b"]) {
            
            NSLog(@"取消成功");
            
        }else if ([endData isEqualToString:@"05"]){
            
            NSLog(@"取消失败");
            
        }

        
    }else if ([headData isEqualToString:@"c081"]){//获取通知状态
        
        if ([endData isEqualToString:@"00"]||[endData isEqualToString:@"05"]) {
            
            NSLog(@"");
            [self wwcheck];
            
        }else if ([endData isEqualToString:@"01"]){
            
            NSLog(@"已经注册");
            
        }
        
    }else if ([headData isEqualToString:@"c081"]){//通知注册结果
        
        if ([endData isEqualToString:@"0b"]) {
            
            NSLog(@"注册成功");
            
        }else if ([endData isEqualToString:@"05"]){
            
            NSLog(@"注册失败");
            
        }
        
    }else if ([headData isEqualToString:@"4003"]){//通知注册结果
        
        

        if ([endData isEqualToString:@"ea"]) {
            
            NSLog(@"通知app耳机的出行模式打开");
            [self tophonesuccess];
            self.GetheadsetVoice = 3;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];

        }else if ([endData isEqualToString:@"eb"]){
            
            NSLog(@"通知app耳机的监听模式打开");
            [self tophonesuccess];
            self.GetheadsetVoice = 4;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];

            
        }else if ([endData isEqualToString:@"ec"]){
            
            NSLog(@"通知app耳机的正常模式打开");
            [self tophonesuccess];
            self.GetheadsetVoice = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];


        }else if ([endData isEqualToString:@"ed"]){
            
            NSLog(@"通知app耳机的风中模式打开");
            [self tophonesuccess];
            self.GetheadsetVoice = 1;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];
            
            
        }else if ([endData isEqualToString:@"ee"]){
            
            NSLog(@"通知app耳机的室内模式打开");
            [self tophonesuccess];
            self.GetheadsetVoice = 2;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetHEADSETVOICE object:nil];
            
            
        }else{
            
            //失败
            NSString *sendata = @"aa01c00305";
            const char *buf = [sendata UTF8String];
            NSMutableData *data = [NSMutableData data];
            if (buf)
            {
                uint32_t len = (uint32_t)strlen(buf);
                
                char singleNumberString[3] = {'\0', '\0', '\0'};
                uint32_t singleNumber = 0;
                for(uint32_t i = 0 ; i < len; i+=2)
                {
                    if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
                    {
                        singleNumberString[0] = buf[i];
                        singleNumberString[1] = buf[i + 1];
                        sscanf(singleNumberString, "%x", &singleNumber);
                        uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                        [data appendBytes:(void *)(&tmp) length:1];
                    }
                    else
                    {
                        break;
                    }
                }
                
                NSLog(@"发送%@",data);
                [[EADSessionController sharedController] writeData:data];
            }

        }
        
    }


     
}

- (void)tophonesuccess{
    
    //成功
    NSString *sendata = @"aa01c003000b";
    const char *buf = [sendata UTF8String];
    NSMutableData *data = [NSMutableData data];
    if (buf)
    {
        uint32_t len = (uint32_t)strlen(buf);
        
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [data appendBytes:(void *)(&tmp) length:1];
            }
            else
            {
                break;
            }
        }
        
        NSLog(@"发送%@",data);
        [[EADSessionController sharedController] writeData:data];
    }

}

#pragma mark - --------------------------lighting--------------------------
//已经有设备连接
-(void)isDeviceToConnect{
    
    [self.deviceToConnect openSessionForProtocol:PROTOCOL andIsEqualToProductName:PRODUCTNAME andeModeName:MODELNAME andVersion:SystemVersion];
    NSLog(@"Lightning耳机已经连接");

}

//发现设备且核对信息
- (void)foundEquipmentAndCheckTheInformation{
    
    self.lightingConnet = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lightingconnect" object:nil];
}


//设备断开连接
-(void)undeviceToConnect{
    
  //  [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"断开连接")];
    
    [SVProgressHUD dismiss];
    self.lightingConnet = NO;
    if (self.avAudioPlayer.isPlaying == YES)
    {
        self.isBurn = NO;
        [self stop];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lightingDisconnect" object:nil];
    NSLog(@"Lightning耳机已经断开连接");
}

// 设备断开连接
- (void)disconnectDevice
{
    self.lightingConnet = NO;
    if (self.avAudioPlayer.isPlaying == YES)
    {
        self.isBurn = NO;
        [self stop];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lightingDisconnect" object:nil];
    NSLog(@"Lightning耳机已经断开连接");
}

//还不是最新版本，提示更新
-(void)isNotTheLatestVersion{
    NSArray *array = [LightningModel selectAllObject];
    LightningModel *light = array.lastObject;
    light.isLastVersion = @"NO";
    SAVE_BOOL(NO, THELASTESTVERSION);
    self.lightingConnet = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lightingconnect" object:nil];
    NSLog(@"当前版本：%@最新版本：%@",self.deviceToConnect.versionString,self.deviceToConnect.latestVersion);
}

//已经是最新版本
-(void)isTheLatestVersion{
    NSArray *array = [LightningModel selectAllObject];
    LightningModel *light = array.lastObject;
    light.isLastVersion = @"YES";
    SAVE_BOOL(YES, THELASTESTVERSION);
    self.lightingConnet = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"lightingconnect" object:nil];
    NSLog(@"当前版本：%@最新版本：%@",self.deviceToConnect.versionString,self.deviceToConnect.latestVersion);

}

//获取安装进度
-(void)getProgressView:(float)numbel{
    
//    NSString *time =  [NSString stringWithFormat:@"%.0lf%%",numbel*100];
    
//    [SVProgressHUD showWithStatus:time];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:@(numbel)];
    
    if (numbel == 1.0f) {
        
        SAVE_BOOL(YES, THELASTESTVERSION);

        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateOK" object:nil];
    }
}

- (void)update{
    

    [self.deviceToConnect update];

}

#pragma mark - --------------------------musciPlay--------------------------

- (void)againMusic{
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:MyNSLocalizedString(@"提示") message:MyNSLocalizedString(@"煲机完成") delegate:self cancelButtonTitle:MyNSLocalizedString(@"取消") otherButtonTitles:MyNSLocalizedString(@"确认"), nil];
    
    
    [alertView show];
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"clickButtonAtIndex:%d",(int)buttonIndex);
    //index为-1则是取消，
    if (buttonIndex == 1) {
        
        if (self.burnMode == 0) {
            
            REMOVE_OBJECT(LIGHTINGTOTALPALTTIME);

        }else if (self.burnMode == 1){
            
            
          NSArray *deviceArray = [LINNERBurnTime selectObjectPredicateWithFormat:[NSString stringWithFormat:@"where macAddress = '%@'",self.accessory.serialNumber]];
            if (deviceArray.count != 0) {
                LINNERBurnTime *time = [deviceArray lastObject];
                [time deleteObject];
            }
            
            
        }
        
        [self judgeBurnMusicstage];
    }
}

- (void)judgeBurnMusicstage{
    
    
    if (self.burnMode == 0) {
        
        if ([EXRACT_OBJECT(LIGHTINGTOTALPALTTIME) length] == 0) {//容错处理
            
            SAVE_OBJECT(@"0", LIGHTINGTOTALPALTTIME);
        }
        
        NSString *totalTime = EXRACT_OBJECT(LIGHTINGTOTALPALTTIME);
        
        
        NSString *string;
        if ([totalTime longLongValue] <= 43200) {//12小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Pink_Noise_-15dB" ofType:@"mp3"];
            
        }else if ([totalTime longLongValue] > 43200 && [totalTime longLongValue] <= 86400){//24小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Square_Noise_150Hz_-20dB" ofType:@"mp3"];
            
        }else if ([totalTime longLongValue] > 84400 && [totalTime longLongValue] <= 129600){//36小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Brazil music_-15dB" ofType:@"mp3"];
            
        }else{
            
            [self againMusic];
            
            return;
        }
        
        //把音频文件转换成url格式
        NSURL *url = [NSURL fileURLWithPath:string];
        //初始化音频类 并且添加播放文件
        self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        //设置代理
        self.avAudioPlayer.delegate = self;
        
        
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];
        //设置音乐播放次数  -1为一直循环
        self.avAudioPlayer.numberOfLoops = -1;
        
        //设置初始音量大小
        
        
        //预播放
        //  [self.avAudioPlayer prepareToPlay];

    }else if (self.burnMode == 1){
        
        
        NSString *Time = nil;
        NSArray *deviceArray = [LINNERBurnTime selectObjectPredicateWithFormat:[NSString stringWithFormat:@"where macAddress = '%@'",self.accessory.serialNumber]];
        if (deviceArray.count == 0) {//新增的设备
            
            LINNERBurnTime *burnTime = [[LINNERBurnTime alloc]init];
            burnTime.macAddress = self.accessory.serialNumber;
            [burnTime insertObject];
            
        }else{//数据库中已经存在的设备
            LINNERBurnTime *burnTime = [deviceArray lastObject];
            Time = burnTime.time;
            
        }
        
        

        NSString *totalTime = Time;
        
        
        NSString *string;
        if ([totalTime longLongValue] <= 43200) {//12小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Pink_Noise_-15dB" ofType:@"mp3"];
            
        }else if ([totalTime longLongValue] > 43200 && [totalTime longLongValue] <= 86400){//24小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Square_Noise_150Hz_-20dB" ofType:@"mp3"];
            
        }else if ([totalTime longLongValue] > 84400 && [totalTime longLongValue] <= 129600){//36小时
            
            string = [[NSBundle mainBundle] pathForResource:@"Brazil music_-15dB" ofType:@"mp3"];
            
        }else{
            
            [self againMusic];
            
            return;
        }
        
        //把音频文件转换成url格式
        NSURL *url = [NSURL fileURLWithPath:string];
        //初始化音频类 并且添加播放文件
        self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        //设置代理
        self.avAudioPlayer.delegate = self;
        
        
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];
        //设置音乐播放次数  -1为一直循环
        self.avAudioPlayer.numberOfLoops = -1;
        
        //设置初始音量大小
        self.avAudioPlayer.volume = 0.5f;
        
    }
    
}





//播放
- (void)play
{

    self.avAudioPlayer.volume = 0.5f;

    if (self.burnMode == 0) {
        //获取当前的播放总进度
        everyTime = EXRACT_OBJECT(LIGHTINGTOTALPALTTIME);
        if ([everyTime longLongValue] <= 43200) {//12小时
            
            tagIndex = 0;
            
        }else if ([everyTime longLongValue] > 43200 && [everyTime longLongValue] <= 86400){//24小时
            
            tagIndex = 1;
            
        }else if ([everyTime longLongValue] > 84400 && [everyTime longLongValue] <= 129600){//36小时
            
            tagIndex = 2;
            
        }else{
            
            tagIndex = 3;
            
            [self againMusic];
            
            return;
        }
        
        [self.avAudioPlayer play];

    }else if (self.burnMode == 1){
        
        
        NSString *Time = nil;
        NSArray *deviceArray = [LINNERBurnTime selectObjectPredicateWithFormat:[NSString stringWithFormat:@"where macAddress = '%@'",self.accessory.serialNumber]];
        if (deviceArray.count == 0) {//新增的设备
            
            LINNERBurnTime *burnTime = [[LINNERBurnTime alloc]init];
            burnTime.macAddress = self.accessory.serialNumber;
            [burnTime insertObject];
            
        }else{//数据库中已经存在的设备
            LINNERBurnTime *burnTime = [deviceArray lastObject];
            Time = burnTime.time;
            
        }
        
        everyTime = Time;
        
        if ([everyTime longLongValue] <= 43200) {//12小时
            
            tagIndex = 0;
            
        }else if ([everyTime longLongValue] > 43200 && [everyTime longLongValue] <= 86400){//24小时
            
            tagIndex = 1;
            
        }else if ([everyTime longLongValue] > 84400 && [everyTime longLongValue] <= 129600){//36小时
            
            tagIndex = 2;
            
        }else{
            
            tagIndex = 3;
            
            [self againMusic];
            
            return;
        }
        
        [self.avAudioPlayer play];

        
        
    }
    
    
    
}
//暂停
- (void)pause
{

    [self.avAudioPlayer pause];
    [self getNowTimeDifference];
}
//停止
- (void)stop
{
 
    self.avAudioPlayer.currentTime = 0;  //当前播放时间设置为0
    [self.avAudioPlayer stop];
    [self getNowTimeDifference];

    [self cancelTimeLighting];
}


//settime
- (void)setTimeLighting{
    
    __weak typeof(self) weakself = self;

    if (self.burnMode == 0) {
        
        NSLog(@"开始定时器");
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT));
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            
            [weakself getNowTimeDifference];
            if (tagIndex == 0) {
                
                if ([EXRACT_OBJECT(LIGHTINGTOTALPALTTIME) longLongValue] >= 43200) {
                    
                    [self stop];
                    [self judgeBurnMusicstage];
                    [self play];
                }else{
                    
                    
                }
                
            }else if (tagIndex == 1){
                
                if ([EXRACT_OBJECT(LIGHTINGTOTALPALTTIME) longLongValue] >= 86400) {
                    [self stop];
                    [self judgeBurnMusicstage];
                    [self play];
                    
                }else{
                    
                    
                }
                
            }else if (tagIndex == 2){
                
                if ([EXRACT_OBJECT(LIGHTINGTOTALPALTTIME) longLongValue] >= 129600) {
                    [self stop];
                    [self judgeBurnMusicstage];
                    
                }else{
                    
                    
                }
                
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LightingSource" object:nil];
            NSLog(@"发送刷新数据");
        });
        dispatch_resume(timer);

        
    }else if (self.burnMode == 1){
        
        NSLog(@"开始定时器");
        NSInteger timecount;
        NSArray *deviceArray = [LINNERBurnTime selectObjectPredicateWithFormat:[NSString stringWithFormat:@"where macAddress = '%@'",self.accessory.serialNumber]];
        {
            LINNERBurnTime *time = [deviceArray lastObject];
            NSInteger totalTime = [time.time integerValue];
            timecount = totalTime;
        }
        

        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT));
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            
            [weakself getNowTimeDifference];
            if (tagIndex == 0) {
                
                if (timecount >= 43200) {
                    
                    [self stop];
                    [self judgeBurnMusicstage];
                    [self play];
                }else{
                    
                    
                }
                
            }else if (tagIndex == 1){
                
                if (timecount >= 86400) {
                    [self stop];
                    [self judgeBurnMusicstage];
                    [self play];
                    
                }else{
                    
                    
                }
                
            }else if (tagIndex == 2){
                
                if (timecount >= 129600) {
                    [self stop];
                    [self judgeBurnMusicstage];
                    
                }else{
                    
                    
                }
                
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LightingSource" object:nil];
            NSLog(@"发送刷新数据");
        });
        dispatch_resume(timer);

        
    }
    
    
    
}

- (void)cancelTimeLighting{
    
    if(timer){
        dispatch_source_cancel(timer);
        timer = nil;
    }
    NSLog(@"定时器取消");

}
- (void)getNowTimeDifference{
    

//  定时器每次加20秒允许有5s的误差
    if (self.burnMode == 0) {
        
        
        NSString *total = [NSString stringWithFormat:@"%lld",1+[EXRACT_OBJECT(LIGHTINGTOTALPALTTIME) longLongValue]];
        NSLog(@"总时间:%@",total);
        
        SAVE_OBJECT(total, LIGHTINGTOTALPALTTIME);
        
    }else if (self.burnMode == 1){
        
        
        NSArray *deviceArray = [LINNERBurnTime selectObjectPredicateWithFormat:[NSString stringWithFormat:@"where macAddress = '%@'",self.accessory.serialNumber]];
        if (deviceArray.count != 0) {
            LINNERBurnTime *time = [deviceArray lastObject];
            NSInteger totalTime = [time.time integerValue];
            totalTime += 1;
            time.time = [NSString stringWithFormat:@"%ld",totalTime];
            [time updateObject];
        }
        
    }

    
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
    // 当音频播放过程中被中断时，执行该方法。比如：播放音频时，电话来了！
    // 这时候，音频播放将会被暂停。
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stop" object:nil];

}


//获取当前时间戳方法(以秒为单位)
+ (NSString *)getNowTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
   // NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

#pragma mark - AppDelegate globalDelegate
+ (AppDelegate *)globalDelegate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
   // [self EAS];
    
    if (self.linnerConnet == NO) {
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"DislinnerConnect" object:nil];

    }

}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:
    
}


@end
